/**
 * 封装axios
 * 设置请求拦截器
 * 设置响应拦截器
 * 设置统一的错误处理
 * 设置通用的请求方法
 * */
import Vue from 'vue'
import axios from 'axios'
import router from '@/router'
import qs from 'qs'

/* 设置axios请求路径的前缀 */
axios.defaults.baseURL = process.env.VUE_APP_BASE_API

/* 设置超时时间 */
axios.defaults.timeout = 1000 * 10

/* 设置统一post请求头 */
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'

/* 设置请求拦截器 */
axios.interceptors.request.use(request => {
  /* 获取token */
  const token = Vue.$cookies.get('token')
  if (token) {
    request.headers.token = token
  }
  return request
}, error => {
  return Promise.error(error)
})

/* 设置响应拦截器 */
axios.interceptors.response.use(response => {
  if (response.status === 200) {
    if (response.data.code === 401) {
      Vue.prototype.$alert(`${response.data.msg},请重新登录！`, { type: 'error' }).then(() => {
        router.replace('/login')
      })
    } else {
      if (response.data.code === 200) {
        return Promise.resolve(response)
      } else {
        Vue.prototype.$alert(response.data.msg, { type: 'error' }).then(() => {
          return Promise.resolve(response)
        })
      }
    }
  } else {
    Vue.prototype.$alert(response.statusText, { type: 'error' }).then(() => {
      return Promise.reject(response)
    })
  }
}, error => {
  return Promise.error(error)
})

/* 设置通用的请求方法 */
const http = {
  get (url, params) {
    return new Promise((resolve, reject) => {
      axios.get(url, { params }).then(({ data }) => {
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  post (url, params, isQs = false) {
    return new Promise((resolve, reject) => {
      axios.post(url, isQs ? qs.stringify(params) : params).then(({ data }) => {
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  delete (url, params) {
    return new Promise((resolve, reject) => {
      axios.delete(url, { params }).then(({ data }) => {
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

Vue.prototype.$http = http
Vue.prototype.$axios = axios
